/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from 'react';
import { Input, Button, message } from 'antd';
import KbIcon from '@/components/KbIcon';
import { connect } from 'dva';
import { isArray } from 'lodash';

const { TextArea } = Input;

@connect(({ loading }) => ({
  parsing: loading.effects['address/parseInfo'],
}))
class AiInput extends Component {
  static defaultProps = { onParse: () => {} };

  constructor(props) {
    super(props);
    this.state = {
      value: '',
    };
  }

  onChange = e => {
    const { value } = e.target;
    this.setState({ value });
  };

  // 识别
  onParse = () => {
    const { value: address } = this.state;
    if (!address) return;
    const { dispatch, type, onParse } = this.props;
    const payload = { address };
    if (type === 'send') {
      payload.type = 0;
    }
    dispatch({
      type: 'address/parseInfo',
      payload,
    }).then(res => {
      const { data, msg } = res;
      if (isArray(data) && data.length) {
        const list = [];
        data.map(item => {
          const item_ = {};
          Object.keys(item).map(key => {
            item_[key.replace('shipping_', '')] = item[key];
          });
          list.push(item_);
        });
        onParse(type === 'send' ? list[0] : list);
        this.setState({value:''})
      } else {
        message.error(msg);
      }
    });
  };

  render() {
    const { type, parsing } = this.props;
    const { value } = this.state;
    return (
      <>
        <TextArea
          style={{ height: 150 }}
          placeholder={`输入姓名，地址，电话${type ==='send'?'':'，备注'}，用空格隔开${
            type === 'send' ? '' : '（可添加多个地址，换行隔开）'
          }`}
          value={value}
          onChange={this.onChange}
        />
        <Button
          disabled={!value || parsing}
          type="primary"
          ghost
          style={{ marginTop: 12 }}
          onClick={this.onParse}
        >
          <KbIcon type={parsing ? 'loading' : 'icon-scan'} />
          识别
        </Button>
      </>
    );
  }
}

export default AiInput;
